package com.seafood.service.impl;

import com.seafood.dto.PaymentRequestDTO;
import com.seafood.dto.PaymentResponseDTO;
import com.seafood.entity.Order;
import com.seafood.exception.BusinessException;
import com.seafood.repository.OrderRepository;
import com.seafood.service.OrderService;
import com.seafood.service.PaymentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 支付服务实现类
 */
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class PaymentServiceImpl implements PaymentService {
    
    private final OrderRepository orderRepository;
    private final OrderService orderService;
    
    @Override
    public PaymentResponseDTO createPayment(PaymentRequestDTO paymentRequest) {
        // 验证订单是否存在
        Order order = orderRepository.findByOrderNumber(paymentRequest.getOrderNumber())
                .orElseThrow(() -> new BusinessException("订单不存在"));
        
        // 验证订单金额是否匹配
        if (order.getFinalAmount().compareTo(paymentRequest.getAmount()) != 0) {
            throw new BusinessException("支付金额与订单金额不匹配");
        }
        
        // 验证订单状态是否为待支付
        if (order.getStatus() != Order.OrderStatus.PENDING) {
            throw new BusinessException("订单状态不允许支付");
        }
        
        // 创建模拟支付响应
        PaymentResponseDTO response = new PaymentResponseDTO();
        String paymentId = "PAY" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
        
        response.setPaymentId(paymentId);
        response.setOrderNumber(paymentRequest.getOrderNumber());
        response.setAmount(paymentRequest.getAmount());
        response.setPaymentMethod(paymentRequest.getPaymentMethod());
        response.setStatus("PENDING");
        response.setSuccess(true);
        response.setMessage("支付订单创建成功");
        response.setCreatedAt(LocalDateTime.now().toString());
        
        // 设置模拟支付链接
        response.setPayUrl("/payment/simulate?paymentId=" + paymentId);
        
        return response;
    }
    
    @Override
    public void simulatePaymentSuccess(String orderNumber) {
        // 验证订单是否存在
        Order order = orderRepository.findByOrderNumber(orderNumber)
                .orElseThrow(() -> new BusinessException("订单不存在"));
        
        // 验证订单状态是否为待支付
        if (order.getStatus() != Order.OrderStatus.PENDING) {
            throw new BusinessException("订单状态不允许支付");
        }
        
        // 更新订单状态为已支付
        orderService.updateOrderStatus(order.getId(), Order.OrderStatus.PAID);
    }
    
    @Override
    public PaymentResponseDTO getPaymentStatus(String paymentId) {
        // 模拟支付状态查询
        PaymentResponseDTO response = new PaymentResponseDTO();
        response.setPaymentId(paymentId);
        response.setStatus("SUCCESS"); // 模拟支付成功
        response.setSuccess(true);
        response.setMessage("支付成功");
        return response;
    }
    
    @Override
    public void handlePaymentSuccess(String orderNumber) {
        // 处理支付成功逻辑，更新订单状态
        Order order = orderRepository.findByOrderNumber(orderNumber)
                .orElseThrow(() -> new BusinessException("订单不存在"));
        
        if (order.getStatus() == Order.OrderStatus.PENDING) {
            orderService.updateOrderStatus(order.getId(), Order.OrderStatus.PAID);
        }
    }
}